﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.IO;
//using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.FileSystem;


namespace DotNetNuke.Modules.UserDefinedTable
{


  /// <summary>
  /// base object for DataTypeDocument fields. Document stores data into given folder
  /// and original filename is replaced by GUID
  /// </summary>
  internal class DocumentObject
  {

    
    protected struct documentInfo
    {
      public string FileID;
      public string StorageFileName;
      public string OriginalFileName;
    }




    protected documentInfo _documentInfo;
    protected int _moduleID;
    protected Hashtable _moduleSettings;
    protected PortalSettings _portalSettings;
    protected FileController _fc;



    public DocumentObject(int moduleID, string DocMoniker)
    {
      this._portalSettings = PortalController.GetCurrentPortalSettings();
      ModuleController mc = new ModuleController();
      this._moduleID = moduleID;
      this._moduleSettings = mc.GetModuleSettings(this._moduleID);
      this._documentInfo = _deserializeDocumentInfo(DocMoniker);
      _fc = new FileController();
    }




    public DocumentObject(int moduleID, FileUpload upload, string strDocumentFolder)
    {
      string ParentFolderName;
      this._portalSettings = PortalController.GetCurrentPortalSettings();
      ModuleController mc = new ModuleController();
      this._moduleID = moduleID;
      this._moduleSettings = mc.GetModuleSettings(this._moduleID);

      if (!upload.HasFile)
        throw new ArgumentNullException();
      
      if (this._portalSettings.ActiveTab.ParentId == this._portalSettings.SuperTabId)
        ParentFolderName = DotNetNuke.Common.Globals.HostMapPath;
      
      else

        ParentFolderName = this._portalSettings.HomeDirectoryMapPath;
      
      ParentFolderName = ParentFolderName + strDocumentFolder;
      string strExtension = Path.GetExtension(upload.PostedFile.FileName);
      string SecureFile = Guid.NewGuid().ToString() + strExtension;
      
      FileSystemUtils.UploadFile(ParentFolderName.Replace("/", @"\"), upload.PostedFile, SecureFile, false);
      FileController fc = new FileController();
      FolderController foC = new FolderController();
      FolderInfo fldr = new FolderInfo();
      
      fldr = foC.GetFolder(this._portalSettings.PortalId, strDocumentFolder, false);
      //DotNetNuke.Services.FileSystem.FileInfo fi = new DotNetNuke.Services.FileSystem.FileInfo();
      DotNetNuke.Services.FileSystem.FileInfo fi = fc.GetFile(SecureFile, this._portalSettings.PortalId, fldr.FolderID);

      if (fi == null)
        throw new InvalidOperationException("file not found");
      
      this._documentInfo = new documentInfo();
      this._documentInfo.OriginalFileName = Path.GetFileName(upload.PostedFile.FileName);
      this._documentInfo.StorageFileName = SecureFile;
      this._documentInfo.FileID = "FileID=" + fi.FileId.ToString();
    }




    protected static documentInfo _deserializeDocumentInfo(string rawDbValue)
    {
      documentInfo retVal = new documentInfo();
      string[] tmp = rawDbValue.Split(new char[] { '|' });
      retVal.FileID = tmp[0];
      retVal.OriginalFileName = tmp[1];
      return retVal;
    }




    public static string DeleteDocument(ref string DocMoniker)
    {
      FileController fc = new FileController();
      documentInfo docInfo = _deserializeDocumentInfo(DocMoniker);

      DotNetNuke.Services.FileSystem.FileInfo f = fc.GetFileById(int.Parse(UrlUtils.GetParameterValue(docInfo.FileID)), PortalController.GetCurrentPortalSettings().PortalId);
      if (f == null)
        throw new InvalidOperationException("file not found");
      
      return FileSystemUtils.DeleteFile(f.PhysicalPath, PortalController.GetCurrentPortalSettings());
    }




    public virtual object ToLink()
    {
      bool bolNewWindow = true;
      FileController fc = new FileController();
      string strFieldLinkValue = string.Empty;
      string strFileId = URLUtil.StripURL(ref this._documentInfo.FileID);
      DotNetNuke.Modules.UserDefinedTable.TokenReplace objTokenReplace = new DotNetNuke.Modules.UserDefinedTable.TokenReplace();
      string strURL = "";
    
      if (!string.IsNullOrEmpty(strFileId))
      {
        strURL = this.ToUrl();
        string strDisplayName = this._documentInfo.OriginalFileName;
        strFieldLinkValue = string.Format("<!--{0}--><a href=\"{1}\" {2}>{3}</a>", strDisplayName, strURL, (bolNewWindow ? " target=\"_blank\"" : "").ToString(), strDisplayName);
      }
      return strFieldLinkValue;
    }




    public object ToMoniker()
    {
      return string.Format("{0}|{1}", this._documentInfo.FileID, this._documentInfo.OriginalFileName);
    }




    public virtual string ToUrl()
    {
      return HttpUtility.HtmlEncode(DotNetNuke.Common.Globals.LinkClick(this._documentInfo.FileID, this._portalSettings.ActiveTab.TabID, this._moduleID, false, Utilities.CBoolN((this._moduleSettings[SettingName.ForceDownload]), false)));
    }





    public string FileID
    { get { return this._documentInfo.FileID; } }





    /// <summary>
    /// returns downloaded document size in bytes
    /// </summary>
    public int DocumentSize
    {
      get
      {
        //'If(String.IsNullOrEmpty(DocMoniker)) then
        //'  Return 0
        //'End If

        //'Dim docInfo As documentInfo = _deserializeDocumentInfo(DocMoniker)
        //'Dim fc As New FileController
        DotNetNuke.Services.FileSystem.FileInfo fi = _fc.GetFileById(int.Parse(UrlUtils.GetParameterValue(_documentInfo.FileID)), PortalController.GetCurrentPortalSettings().PortalId);

        if (fi == null)
          return 0;
        else
          return fi.Size;

      }
    }




    //public static DocumentObject Create(int moduleID, FileUpload upload, string strDocumentFolder, int MaxFileSizeBytes)
    public static DocumentObject Create(int moduleID, FileUpload upload, string strDocumentFolder)
    {
      DocumentObject DocObj;

      try
      {
        //DocObj = New DocumentObject(moduleID, upload, strDocumentFolder, MaxFileSizeBytes)
        DocObj = new DocumentObject(moduleID, upload, strDocumentFolder);
      }
      catch (Exception e)
      {
        DocObj = null;
      }

      return DocObj;

    }




  }

}

